import { useState, useEffect, useRef, useCallback } from "react";
import { Modal } from "antd";
import printTemplateService from "@/api/services/tool/printTemplateService";
import { defaultElementTypeProvider, hiprint } from "@/components/hiprint";
import { PaperType, PrintElement } from "../models/types";
import { toast } from "sonner";

interface PrintElementTypeContext {
	addPrintElementTypes: (providerName: string, groups: hiprint.PrintElementTypeGroup[]) => void;
}

interface ElementTypeProvider {
	addElementTypes: (context: PrintElementTypeContext) => void;
}

export const usePrintDesigner = () => {
	const [loading, setLoading] = useState(true);
	const [paperTypes, setPaperTypes] = useState<Record<string, PaperType>>({
		A3: { width: 420, height: 296.6 },
		A4: { width: 210, height: 296.6 },
		A5: { width: 210, height: 147.6 },
		B3: { width: 500, height: 352.6 },
		B4: { width: 250, height: 352.6 },
		B5: { width: 250, height: 175.6 },
	});
	const [curPaper, setCurPaper] = useState<PaperType>(paperTypes.A4);
	const [scaleValue, setScaleValue] = useState(1);
	const [elementTypes, setElementTypes] = useState<PrintElement[]>([]);
	const [jsonDialogVisible, setJsonDialogVisible] = useState(false);
	const [jsonOut, setJsonOut] = useState("");
	const [tidMode, setTidMode] = useState(false);
	const [beautify, setBeautify] = useState(false);
	const [paperWidth, setPaperWidth] = useState("220");
	const [paperHeight, setPaperHeight] = useState("80");

	const hiprintTemplate = useRef<any>(null);
	const previewRef = useRef<any>(null);

	// 计算当前纸张类型
	const curPaperType =
		Object.keys(paperTypes).find(
			(key) => paperTypes[key].width === curPaper.width && paperTypes[key].height === curPaper.height,
		) || "other";

	// 从路由参数获取 templateId
	const getTemplateIdFromRoute = useCallback(() => {
		const searchParams = new URLSearchParams(location.search);
		console.log("访问路径", searchParams);
		return searchParams.get("templateId") || "";
	}, [location.search]);

	// 初始化
	useEffect(() => {
		const init = async () => {
			setLoading(true);
			try {
				// const templateId = getTemplateIdFromRoute(); // 从路由获取
				const templateId = "1951185989532868610";

				//获取打印字段
				const elements = await printTemplateService.getTemplateFields(templateId);
				setElementTypes(elements);

				//获取模板数据
				const templateData = await printTemplateService.getTemplateJson(templateId);
				console.log(elements);
				initHiprint(templateData, elements);
			} catch (error) {
				console.log("初始化Hiprint失败", error);
				toast.error("初始化失败");
			} finally {
				setLoading(false);
			}
		};

		init();
	}, []);

	const initHiprint = (templateData: any, elementTypes: PrintElement[]) => {
		const customElementTypeProvider: (options?: any) => ElementTypeProvider = (function () {
			return function (options?: any): ElementTypeProvider {
				const addElementTypes = function (context: PrintElementTypeContext): void {
					context.addPrintElementTypes("defaultProvider", [
						new hiprint.PrintElementTypeGroup("常规", [
							{
								tid: "common.text",
								text: "文本",
								type: "text",
								options: {
									textAlign: "center",
									textContentVerticalAlign: "middle",
								},
							},
							{
								tid: "common.image",
								text: "图片",
								type: "image",
							},
						]),
						new hiprint.PrintElementTypeGroup("字段", elementTypes),
						new hiprint.PrintElementTypeGroup("辅助", [
							{
								tid: "testModule.hline",
								text: "横线",
								type: "hline",
							},
							{
								tid: "testModule.vline",
								text: "竖线",
								type: "vline",
							},
							{
								tid: "testModule.rect",
								text: "矩形",
								type: "rect",
							},
							{
								tid: "testModule.oval",
								text: "椭圆",
								type: "oval",
							},
							{
								tid: "aProviderModule.barcode",
								title: "条形码",
								type: "barcode",
							},
							{
								tid: "aProviderModule.qrcode",
								title: "二维码",
								type: "qrcode",
							},
						]),
					]);
				};

				return {
					addElementTypes,
				};
			};
		})();

		// 初始化打印插件
		hiprint.init({
			providers: [customElementTypeProvider()],
		});

		// 配置
		hiprint.setConfig({
			movingDistance: 2.5,
			text: {
				supportOptions: [
					{
						name: "styler",
						hidden: true,
					},
					{
						name: "formatter",
						hidden: true,
					},
				],
			},
		});

		// 先清空, 避免重复构建
		$(".hiprintEpContainer").empty();
		//应用在init中的provider，第二个参数是对应的addPrintElementTypes名称
		hiprint.PrintElementTypeManager.build(".hiprintEpContainer", "defaultProvider");

		hiprintTemplate.current = new hiprint.PrintTemplate({
			template: templateData,
			settingContainer: "#PrintElementOptionSetting",
		});

		hiprintTemplate.current.design("#hiprint-printTemplate");
		setScaleValue(hiprintTemplate.current.editingPanel.scale || 1);
	};

	// 设置纸张
	const setPaper = (type: string, value: PaperType) => {
		try {
			setCurPaper({ type, ...value });
			hiprintTemplate.current?.setPaper(value.width, value.height);
		} catch (error) {
			toast.error(`操作失败: ${error}`);
		}
	};

	// 自定义纸张
	const otherPaper = () => {
		const value = {
			width: Number(paperWidth),
			height: Number(paperHeight),
		};
		setPaper("other", value);
	};

	// 缩放
	const changeScale = (zoomIn: boolean) => {
		let newScale = zoomIn ? scaleValue + 0.1 : scaleValue - 0.1;
		newScale = Math.max(0.5, Math.min(5, newScale));

		hiprintTemplate.current?.zoom(newScale);
		setScaleValue(newScale);
	};

	// 元素对齐
	const setElsAlign = (alignType: string) => {
		hiprintTemplate.current?.setElsAlign(alignType);
	};

	// 全选
	const selectAll = () => {
		hiprintTemplate.current?.selectAllElements();
	};

	// 预览
	const preView = () => {
		previewRef.current?.show(hiprintTemplate.current, printData);
	};

	// 打印
	const print = () => {
		if (window.hiwebSocket?.opened) {
			hiprintTemplate.current?.print2(printData, {
				printer: "",
				title: "hiprint测试打印",
			});
		} else {
			toast.error("客户端未连接,无法直接打印");
		}
	};

	// 清空
	const clearPaper = () => {
		Modal.confirm({
			title: "警告",
			content: "是否确认清空模板信息?",
			onOk: () => {
				try {
					hiprintTemplate.current?.clear();
				} catch (error) {
					toast.error(`操作失败: ${error}`);
				}
			},
		});
	};

	// 保存
	const save = async () => {
		setLoading(true);
		try {
			const templateJson = JSON.stringify(hiprintTemplate.current?.getJson());
			await printTemplateService.saveDesignerJson({
				id: getTemplateIdFromRoute(),
				templateJson,
			});
			toast.success("保存成功");
		} catch (error) {
			toast.error("保存失败");
		} finally {
			setLoading(false);
		}
	};

	// JSON 对话框
	const showJsonDialog = () => {
		setJsonDialogVisible(true);
		setTimeout(() => {
			const json = tidMode ? hiprintTemplate.current?.getJsonTid() : hiprintTemplate.current?.getJson();
			setJsonOut(JSON.stringify(json, null, beautify ? 2 : 0));
		}, 500);
	};

	const hiddenJsonDialog = () => setJsonDialogVisible(false);
	const onJsonModeChange = () => showJsonDialog();

	return {
		loading,
		paperTypes,
		curPaperType,
		scaleValue,
		jsonDialogVisible,
		jsonOut,
		tidMode,
		beautify,
		hiprintTemplate,
		paperWidth,
		paperHeight,

		setPaper,
		changeScale,
		setElsAlign,
		selectAll,
		preView,
		print,
		clearPaper,
		save,
		showJsonDialog,
		hiddenJsonDialog,
		onJsonModeChange,
		otherPaper,
		setPaperWidth,
		setPaperHeight,
	};
};
